﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Model;
using SDT.Site.ViewModels;
using SDT.Lib.Common;
using System.Linq.Dynamic;
using SDT.Site.Properties;
using SDT.Lib.Paging;
namespace SDT.Site.Controllers
{
    public class ArticleController : Controller
    {
        SDTDataContext db = new SDTDataContext();
        public ActionResult Index(int id)
        {
            try
            {
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                a.Categories = db.ArticleCategories.Where(e=>e.ParentID==id && e.ActiveYN==true).OrderBy(string.Format("{0} {1}", "Priority", "asc")).ToList();
                a.Category = db.ArticleCategories.Where(e => e.ID == id).SingleOrDefault();
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }

        public ActionResult List(int id)
        {
            try
            {
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("sitearticle.PageNumber", "page", 1));
                var pageIndex = pageNumber - 1;
                a.Articles = ArticleManager.GetArticles(id, string.Empty, 0, 1, "ID", "desc", pageIndex, Utils.ParseInt(Settings.Default.PageSize));
                a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
                a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                a.Category = db.ArticleCategories.Where(e => e.ID == id).SingleOrDefault();
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }
        public ActionResult Search()
        {
            try
            {
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                var key = UserState.getUserStateFromRequest("sitsearchearticle.Search", "txtArtcleKey", string.Empty).ToString();
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("sitsearchearticle.PageNumber", "page", 1));
                var pageIndex = pageNumber - 1;
                a.Articles = key != string.Empty ? ArticleManager.GetArticles(0, key, 0, 1, "ID", "desc", pageIndex, Utils.ParseInt(Settings.Default.PageSize)) : null;
                a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
                a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                a.Keyword = key;
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        } 
        public ActionResult Details(int id)
        {
            var db = new SDT.Model.SDTDataContext();
            ArticleDetailViewModel a = new ArticleDetailViewModel();
            a.Article = db.Articles.Where(e => e.ID == id).SingleOrDefault();
            a.Article.nViews += 1;
            db.SubmitChanges();
            return View(a);
        }
        public ActionResult Introduction(int id)
        {
            var db = new SDT.Model.SDTDataContext();
            ArticleDetailViewModel a = new ArticleDetailViewModel();
            a.Article = db.Articles.Where(e => e.ID == id).SingleOrDefault();            
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult Lasted(int number, int catid, string title)
        {
            var a = new ArticleListViewModel();
            var db = new SDTDataContext();
            var listArr = catid > 0 ? ArticleManager.GetChild(catid) : new List<int>();
            var l = db.Articles.Where(e => (listArr.Count > 0 ? listArr.ToArray().Contains(e.ArticleCategory.ID) : true) && (e.PubYN == true)).OrderByDescending(e => e.ID).Take(number).ToList();
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult Newest(int number,int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, order, orderDir, number,skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult GetTop(int number, int skip, int catid, string title, string order, string orderDir, string controller, string actionList, string actionDetail)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 1, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult GetByCat(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, order, orderDir, number, skip);            
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            a.Category = db.ArticleCategories.Where(e => e.ID == catid).SingleOrDefault();
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LastedLeft(int number, string title, int catid)
        {
            var a = new ArticleListViewModel();
            var db = new SDTDataContext();
            var listArr =catid>0? ArticleManager.GetChild(catid):new List<int>();
            var l = db.Articles.Where(e => (listArr.Count > 0 ? listArr.ToArray().Contains(e.ArticleCategory.ID) : true) && (e.PubYN == true)).OrderByDescending(e => e.ID).Take(number).ToList();
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LastedRight(int number, string title, int catid)
        {
            var a = new ArticleListViewModel();
            var db = new SDTDataContext();
            var listArr = catid > 0 ? ArticleManager.GetChild(catid) : new List<int>();
            var l = db.Articles.Where(e => (listArr.Count > 0 ? listArr.ToArray().Contains(e.ArticleCategory.ID) : true) && (e.PubYN == true)).OrderByDescending(e => e.ID).Take(number).ToList();
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LastedBottom(int number, string title, int catid)
        {
            var a = new ArticleListViewModel();
            var db = new SDTDataContext();
            var listArr = catid > 0 ? ArticleManager.GetChild(catid) : new List<int>();
            var l = db.Articles.Where(e => (listArr.Count > 0 ? listArr.ToArray().Contains(e.ArticleCategory.ID) : true) && (e.PubYN == true)).OrderByDescending(e => e.ID).Take(number).ToList();
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }

        /// <summary>
        /// Get article focus
        /// </summary>
        /// <param name="number">5</param>
        /// <param name="title"></param>
        /// <returns>List<Article></returns>
        [ChildActionOnly]
        public ActionResult Focus(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 1, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }      
        /// <summary>
        /// Function Name: OtherItems
        /// Description: Get other items in article have catid = catid of current article
        /// </summary>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <param name="title"></param>
        /// <param name="greaterYN"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number, string title,bool greaterYN)
        {
            var a = new ArticleListViewModel();
            var db = new SDTDataContext();
            var current_article = db.Articles.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Articles.Where(e => e.ArticleCategory.ID==current_article.CatID )
                .Where(e=>e.PubYN == true)
                .Where(e => e.ID!=id)
                .Where(e => greaterYN == false ? e.AddDate <= current_article.AddDate : e.AddDate >= current_article.AddDate).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            a.Articles = l;
            return View(a);
        }
        /// <summary>
        /// Function Name: NewestByCat
        /// Description: Get some item in article by category for column right
        /// </summary>
        /// <param name="number"></param>
        /// <param name="skip"></param>
        /// <param name="catid"></param>
        /// <param name="title"></param>
        /// <param name="order"></param>
        /// <param name="orderDir"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult NewestByCat(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult Most(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        /// <summary>
        /// Function name: Guide
        /// Description: Get article by cat
        /// </summary>
        /// <param name="number"></param>
        /// <param name="skip"></param>
        /// <param name="catid"></param>
        /// <param name="title"></param>
        /// <param name="order"></param>
        /// <param name="orderDir"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult Guide(int number, int skip, int catid, string title, string aorder, string aorderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, aorder, aorderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LatestComments(int id,int number)
        {
            var latestC = new List<Comment>();
            try
            {
                latestC = ArticleManager.GetComments(id, true, number).ToList();
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
            }
            return PartialView(latestC);
        }
        [ChildActionOnly]
        public ActionResult Comment(int id)
        {
            var c = new Comment();
            return PartialView(c);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Comment(int id, Comment c)
        {
            try
            {
                UpdateModel(c);
                c.CommentDate = DateTime.Now;
                c.PublishYN = false;
                db.Comments.InsertOnSubmit(c);
                db.SubmitChanges();
                var map = new CommentsInArticle();
                map.CommentID = c.ID;
                map.ArticleID = id;
                db.CommentsInArticles.InsertOnSubmit(map);
                db.SubmitChanges();
                return RedirectToAction("Details", new { id = id });
            }
            catch (Exception exp)
            {
                return RedirectToAction("Details", new { id = id });
            }
        }
        //public ActionResult Create()
        //{
        //    SDTDataContext eDataContext = new SDTDataContext();
        //    ViewData["questionContent"] = Request["questionContent"];
        //    Article a = new Article();
        //    a.ArticleContent = Request["questionContent"];
        //    List<ArticleCategory> ACat = eDataContext.ArticleCategories
        //                                .Where(c => c.ActiveYN == true)
        //                                .Where(c => c.ParentID.HasValue && c.ParentID.Value == Settings.Default.GocBanDocID)
        //                                .ToList();

        //    return View(new ArticleInputModels()
        //    {
        //        ArticleCategory = ACat,
        //        Article = a
        //    });
        //}


        ///// <summary>
        ///// Author: Takamaru Nguyen
        ///// Date: 04/08/2011
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult Create(ArticleInputModels m)
        //{
        //    SDTDataContext eDataContext = new SDTDataContext();
        //    try
        //    {
        //        UpdateModel(m.Article);
        //        m.Article.Priority = 1;
        //        m.Article.AddDate = DateTime.Now;
        //        m.Article.PubYN = false;
        //        m.Article.Summary = m.Article.Title;
        //        m.Article.AddBy = UserManager.GetUserId();
        //        eDataContext.Articles.InsertOnSubmit(m.Article);
        //        eDataContext.SubmitChanges();

        //        return RedirectToAction("Index");
        //    }
        //    catch (Exception ex)
        //    {
        //        List<ArticleCategory> ACat = eDataContext.ArticleCategories
        //                                .Where(c => c.ActiveYN == true)
        //                                .Where(c => c.ParentID.HasValue && c.ParentID.Value == Settings.Default.GocBanDocID)
        //                                .ToList();

        //        return View(new ArticleInputModels()
        //        {
        //            ArticleCategory = ACat,
        //            Article = m.Article
        //        });
        //    }
        //}

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 11/08/2011
        /// </summary>
        public ActionResult Tag(int id, int? page)
        {
            try
            {
                page = page.HasValue && page.Value > 0 ? page.Value : 1;
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("tagarticle.PageNumber", "page", 20));
                ViewData["Keyword"] = db.Tags.Where(t => t.ID == id).FirstOrDefault().Keyword;
                a.Articles = db.ArticleTagMaps.Where(at => at.TagID == id)
                                              .Where(at => at.Article.PubYN == true)
                                              .OrderBy("Article.AddDate Desc")
                                              .Select(at => at.Article)
                                              .ToPagedList(page.Value - 1, pageNumber);

                a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
                a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                //a.Category = db.ArticleTagMaps.Where(e => e.ID == id).SingleOrDefault();
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }

        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 11/08/2011
        /// </summary>
        [ChildActionOnly]
        public ActionResult TagLasted(int id, string title)
        {
            ViewData["title"] = title;
            List<Tag> lTag = db.ArticleTagMaps.Where(vt => vt.ArticleID == id)
                                            .OrderBy("Tag.Keyword desc")
                                            .Select(vt => vt.Tag)
                                            .ToList();

            return View(lTag);
        }
    }
}
